package db;

import java.util.HashMap;
import java.util.Map;

import javax.faces.bean.ApplicationScoped;

import org.apache.log4j.Logger;

import controller.LoginController;

import gameapi.*;

@ApplicationScoped
public class RegisteredUserDb {
	
	private static RegisteredUserDb database;
	private static Map<String, Player> playerList = new HashMap<String,Player>();
	private static Logger logger = Logger.getLogger(RegisteredUserDb.class);
	
	private RegisteredUserDb(){
		
	}
	public static RegisteredUserDb getInstance(){
		if(database == null){
			database = new RegisteredUserDb();
		}
		if(!playerList.containsKey("Computer")){
			Player computerPlayer = new Player();
			computerPlayer.setUserName("Computer");
			computerPlayer.setPassword("");
			computerPlayer.setLoggedIn(true);
			playerList.put(computerPlayer.getUserName(), computerPlayer);
			logger.debug("ComputerPlayer added" + playerList.containsKey(computerPlayer.getUserName()));
		}
		return database;
	}
	
	
	public synchronized void addPlayer(Player player) throws Exception{
		
		if(isAlreadyRegistered(player)){
			logger.info("player: "+player.getUserName()+" already registered");
			throw new Exception("player already registered");
		}else{
			playerList.put(player.getUserName(), player);
			logger.debug("addPlayer " + player.getUserName()+ " registered!");
		}
	}
	
	private synchronized boolean isAlreadyRegistered(Player player){
		logger.debug("isAlreadyRegistered: " + playerList.containsKey(player.getUserName()));
		return playerList.containsKey(player.getUserName());
	}
	public synchronized Player getPlayer(String username){
		return playerList.get(username);	
	}
	public synchronized boolean loginPlayer(Player player) throws Exception{
		logger.debug("loginPlayer");
		if(isAlreadyRegistered(player)){
			if(isValidLogin(player)){
				player.setLoggedIn(true);
				logger.debug("player: "+player.getUserName()+ " logged in");
			}else{
				logger.info("player: "+player.getUserName()+ " incorrect login");
				throw new Exception("Incorrect Login!");
			}
		}else{
			logger.info("player: "+player.getUserName()+ " not registered");
			throw new Exception("You are not registered!");
		}
		return player.isLoggedIn();
	}

	private synchronized boolean isValidLogin(Player player){
		
		Player registeredPlayer = getPlayer(player.getUserName());
		logger.debug("player.pwd: "+ player.getPassword());
		boolean test = player.getPassword().equals(registeredPlayer.getPassword()) ;
		logger.debug(test);
		logger.debug("registeredPlayer: " + registeredPlayer.getUserName() + "  with password: " + registeredPlayer.getPassword() );
		
		return (registeredPlayer != null && !player.isLoggedIn() && player.getPassword().equals(registeredPlayer.getPassword()));

	}


}
